package com.ogawa.chair7808.ui.activity

import android.Manifest
import android.app.AlertDialog
import android.content.*
import android.content.pm.PackageManager
import android.net.ConnectivityManager
import android.net.wifi.WifiManager
import android.os.Handler
import android.text.TextUtils
import android.util.Log
import android.view.KeyEvent
import android.view.View
import android.widget.*
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.ViewModelProviders
import cn.ljuns.logcollector.LogCollector
import com.alibaba.android.arouter.facade.annotation.Route
import com.example.reslib.utils.PreferenceWrapper
import com.example.reslib.utils.ToastUtils
import com.ogawa.base.Constant.*
import com.ogawa.base.mqtt.MqttManager
import com.ogawa.base.utils.CommonUtil
import com.ogawa.base.utils.DebugUtils
import com.ogawa.base.utils.util.MiuiUtils
import com.ogawa.base.utils.util.OSUtils
import com.ogawa.chair7808.R
import com.ogawa.chair7808.manager.DataManager
import com.ogawa.chair7808.manager.DataManager.Companion.inst
import com.ogawa.chair7808.observer.SoftApSucceedObserver
import com.ogawa.chair7808.utils.Activity7808Utils
import com.ogawa.chair7808.viewmodel.HomeActivityViewModel
import com.ogawa.networklib.RetrofitManager
import com.ogawa.networklib.RxObserver
import com.ogawa.networklib.networkBean.BaseResponseBean
import com.ogawa.networklib.networkBean.MqttAccountBean
import io.reactivex.disposables.Disposable
import java.util.*

/**
 * 首页
 */
@Route(path = UrlPathConstant.ACTIVITY_7808_MAIN)
class Home7808Activity7808 : BaseMqtt7808Activity(), View.OnClickListener,
//        IHomeView7506,
        SoftApSucceedObserver.onSoftApLis  {
    private var isExit = false
//    private var mPresenter: HomePresenter7506? = null
    private var mLlAuto: LinearLayout? = null
    private var mLlHand: LinearLayout? = null
    private var mLlAtti: LinearLayout? = null
    private var isFirst = true
    private var mTvNoNet: TextView? = null
    private var mIvWifi: ImageView? = null
    private var mRlRunning: RelativeLayout? = null
    private var mTvRunning: TextView? = null
    private var intentFilter: IntentFilter? = null
    private var mDisposable: Disposable? = null
    private var mCount = 0
    private var mRunning = 0 //1 专业按摩  2 高级按摩
    private var mAutoName: String? = null
    private var mSp: PreferenceWrapper? = null
    private var mSaveVersion = ""
    private var mSaveCount = 0
    private var repeatCount = 0
    private var hasFristConnect //是否首次连接成功websocket过
            = false
    private var viewModel: HomeActivityViewModel? = null
    override fun initTitleBar() {
        super.initTitleBar()
        titleBar.setTitleNameGone()
        titleBar.setBackGone()
        titleBar.showWifi()
    }

    override fun initView(layoutId: Int) {
        super.initView(layoutId)
        viewModel = ViewModelProviders.of(this).get(HomeActivityViewModel::class.java)
        viewModel!!.initMqtt(this)
        mSp = PreferenceWrapper()
        mSaveVersion = mSp!!.getStringValue(Constants.SAVE_VERSION, "")
        mSaveCount = mSp!!.getIntValue(Constants.SAVE_COUNT, 0)
        var curSn = mSp!!.getStringValue(Constant.KEY_SN_7808, "")
        DataManager.inst.setmSn(curSn)
        MqttManager.getInstance().curSn = curSn
        mLlAuto = findViewById(R.id.linear_attitude_adjustment)
        mLlHand = findViewById(R.id.linear_high_massage)
        mLlAtti = findViewById(R.id.linear_professional_massage_7506)
        mTvNoNet = findViewById(R.id.home_tv_nonet)
        mIvWifi = findViewById(R.id.title_wifi)
        mRlRunning = findViewById(R.id.home_rl_running)
        mTvRunning = findViewById(R.id.home_tv_running)
        mLlAtti?.setOnClickListener(this)
        mLlHand?.setOnClickListener(this)
        mLlAuto?.setOnClickListener(this)
        mIvWifi?.setOnClickListener(this)
        mRlRunning?.setOnClickListener(this)
//        mPresenter = HomePresenter7506(this)
        ////输出log
        if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 100)
        }
        LogCollector.getInstance(application)
                .setCleanCache(true) //                .setTag("SendCommond7506","socket7506","TEST")
                .setTag("TEST")
                .setCacheFile(DataManager.creatFile())
                .setCleanCache(true)
                .start()
        SoftApSucceedObserver.getInst().registerObserver(this) //监听是否配网成功
    }

    override fun changeViewByMqttMessage() {
        var isHaveRunning = DataManager.inst.isRunning
        val autoProgram = inst.getDevice7808StateBean().autoProgram
        mRlRunning!!.visibility = View.GONE
    }

    override fun onResume() {
        super.onResume()
        if (!MqttManager.getInstance().isConnect) { //如果Mqtt未连接，则尝试连接
            getMqttAccount()
        }
    }


    override fun loadData() {
        super.loadData()
        if (TextUtils.isEmpty(DataManager.inst.getmSn())) {
//            getPer();
            ToastUtils.showShortToast(this, "请先配置网络")
        } else {
//            showkProgress("初始化中，请稍等...")
        }
    }

    override fun setLayoutId(): Int {
        return R.layout.activity_main_7808
    }

    override fun onClick(v: View) {
        val i = v.id
        if (i == R.id.linear_attitude_adjustment) {
            if (DebugUtils.isDebug){
                Activity7808Utils.startAttitudeAdjustmentActivity(this)
                return
            }
            if (DataManager.inst.isOpen) {
                Activity7808Utils.startAttitudeAdjustmentActivity(this)
            } else {
                ToastUtils.showShortToast(this, "请先开机")
            }
        } else if (i == R.id.linear_professional_massage_7506) { //专业按摩
            if (DebugUtils.isDebug){
                Activity7808Utils.startProfessionMassaActivity(this)
                return
            }
            if (DataManager.inst.isOpen) {
                Activity7808Utils.startProfessionMassaActivity(this)
            } else {
                ToastUtils.showShortToast(this, "请先开机")
            }
        } else if (i == R.id.linear_high_massage) { //高级按摩
            if (DebugUtils.isDebug){
                Activity7808Utils.startAdvancedMassageActivity(this@Home7808Activity7808)
                return
            }
            if (DataManager.inst.isOpen) {
//                自动程序是否在运行
                Activity7808Utils.startAdvancedMassageActivity(this@Home7808Activity7808)
            } else {
                ToastUtils.showShortToast(this, "请先开机")
            }
        } else if (i == R.id.title_wifi) {
            if (CommonUtil.isOPenGPS(this)) {
                getPer()
            } else {
                ToastUtils.showShortToast(this, "配网需要使用定位权限，请先开启定位服务")
            }
        } else if (i == R.id.home_rl_running) {
            DataManager.inst.sendCommond(CommmandNum.PAUSE, "5")
            Log.e("mRUNNING", "$mRunning====")
            if (mRunning == 1) {
                Activity7808Utils.startProMasDetailActivity(this, mAutoName)
            } else {
                Activity7808Utils.startAdvancedMassageActivity(this)
            }
        }
    }

//    fun checkAutoStop() {
//        Observable.interval(0, 100, TimeUnit.MILLISECONDS)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(object : Observer<Long> {
//                    override fun onSubscribe(d: Disposable) {
//                        mDisposable = d
//                    }
//
//                    override fun onNext(aLong: Long) {
//                        val auto = DataManager.getInst().auto
//                        if (mCount < 10) {
//                            if (auto == "0") {
//                                Activity7808Utils.startAdvancedMassageActivity(this@Home7808Activity7808)
//                                mCount = 0
//                                cancleloading()
//                                mDisposable!!.dispose()
//                            }
//                            mCount++
//                        } else {
//                            cancleloading()
//                            mCount = 0
//                            mDisposable!!.dispose()
//                        }
//                    }
//
//                    override fun onError(e: Throwable) {
//                        mCount = 0
//                        mDisposable!!.dispose()
//                        cancleloading()
//                    }
//
//                    override fun onComplete() {}
//                })
//    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitBy2Click()
        }
        return false
    }

    private fun stopAuto() {

//        CommondManager.getInst().sendShortCommond(CommmandNum.FINISH, object : NormalCallback {
//            override fun onSuccess(program: BaseResponse<String>) {
//                Log.e("HomeActivity7506", "onsucceed")
//                showloading()
//                checkAutoStop()
//            }
//
//            override fun onFailure(error: String) {
//                ToastUtils.showShortToast(this@HomeActivity7808, "关闭自动程序失败,请检查网络")
//            }
//        })
    }

    /**
     * 双击退出
     */
    private fun exitBy2Click() {
        var tExit: Timer? = null
        if (isExit == false) {
            isExit = true
            // 准备退出
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show()
            tExit = Timer()
            tExit.schedule(object : TimerTask() {
                override fun run() {
                    isExit = false // 取消退出
                }
            }, 2000)
        } else {
            finish()
            System.exit(0)
        }
    }



    override fun onPermissionSuccess() {
        super.onPermissionSuccess()
        if (OSUtils.isMiui()) {
            val stratTime = System.currentTimeMillis()
            val mWifiManager = this.applicationContext
                    .getSystemService(WIFI_SERVICE) as WifiManager
            val disconnect = mWifiManager.disconnect()
            val endTime = System.currentTimeMillis()
            if (endTime - stratTime > 200 || !disconnect) {
                AlertDialog.Builder(this)
                        .setTitle("请设置权限")
                        .setMessage("请开启WLAN权限，设置为始终运行，以便后续操作")
                        .setNegativeButton(R.string.cancle) { dialog, which -> dialog.dismiss() }
                        .setPositiveButton(R.string.confirm) { dialog, which ->
                            dialog.dismiss()
                            MiuiUtils.jumpToPermissionsEditorActivity(this@Home7808Activity7808)
                        }
                        .show()
            }
        } else {
            Activity7808Utils.startSoftApActivity(this)
        }
    }



//    override fun toProMasDetailActivity(name: String) {
//        if (DataManager.getInst().getValue(CommmandNum.mStatusRunning) != "0") {
//            if (!CommonUtil.isActivityTop(ProMasDetailActivity7808::class.java, this) &&
//                    !CommonUtil.isActivityTop(SoftApOldActivity::class.java, this) &&
//                    !CommonUtil.isActivityTop(SoftApNewActivity::class.java, this)
//                    && !CommonUtil.isActivityTop(ScanShoulderActivity7808::class.java, this) &&
//                    !CommonUtil.isActivityTop(ShouldersAdjustmentActivity7808::class.java, this)) {
//                mAutoName = name
//                mRunning = 1
//                mRlRunning!!.visibility = View.VISIBLE
//                mTvRunning!!.text = "正在执行专业按摩：$name"
//                Activity7808Utils.startProMasDetailActivity(this, name)
//            }
//        }
//    }

//    /**
//     * 高级按摩
//     */
//    override fun toProAdvanceActivity() {
//        if (DataManager.getInst().getValue(CommmandNum.mStatusRunning) != "0") {
//            if (!CommonUtil.isActivityTop(AdvancedMassageActivity7808::class.java, this) && !CommonUtil.isActivityTop(SoftApOldActivity::class.java, this)) {
//                Log.e("AdvancedActivity7506", "111")
//                mRunning = 2
//                mRlRunning!!.visibility = View.VISIBLE
//                mTvRunning!!.text = "正在执行高级按摩"
//                Activity7808Utils.startAdvancedMassageActivity(this)
//            }
//        }
//    }
//
//    override fun closeOther() {
//        if (!CommonUtil.isActivityTop(this.javaClass, this)) {
//            Activity7808Utils.startHomeActivity(this)
//        }
//    }

//    override fun showRunning(show: String, name: String) {
//        Log.e("showRunning", "$name===$show")
//        if (TextUtils.isEmpty(show)) {
//            mRunning = 0
//            mRlRunning!!.visibility = View.GONE
//        } else {
//            if (TextUtils.isEmpty(name)) {
//                mRunning = 2
//            } else {
//                mAutoName = name
//                mRunning = 1
//            }
//            mRlRunning!!.visibility = View.VISIBLE
//            mTvRunning!!.text = show
//        }
//    }


//    override fun isPause(isPause: Boolean) {
//        if (isPause) {
//            pauseTime()
//        } else {
//            reStarTime()
//        }
//    }

//    override fun timeFinish() {
//        super.timeFinish()
//        if (CommonUtil.isActivityTop(Home7808Activity7808::class.java, this)) {
//            showFinishDialog(this, "0") { cancleFinishDialog() }
//        }
//    }

    override fun onDestroy() {
        super.onDestroy()
        DataManager.inst.isConnectSocket = false
//        mPresenter!!.onDestory()
    }

    //wifi 配置成功
    override fun isSoftApOk() {
        MqttManager.getInstance().disconnect()
        getMqttAccount()
    }



    var mqttAccount: String? = null
    var mqttPsw: String? = null

    /**
     * 获取Mqtt账号密码
     */
    fun getMqttAccount() {
        var curSn = PreferenceWrapper().getStringValue(Constant.KEY_SN_7808, "")
        val instance = RetrofitManager.getInstance()
        if (TextUtils.isEmpty(curSn)) {
            return
        }
        onShowLoading()
        instance.getData(instance.apiService.getMqttAccount(curSn) //"OGA75172004080001"
                , object : RxObserver<BaseResponseBean<MqttAccountBean?>?>(this, true) {
            override fun onSuccess(responseBean: BaseResponseBean<MqttAccountBean?>?) {
                onCancleLoading()
                mqttAccount = responseBean?.data?.username
                mqttPsw = responseBean?.data?.password
                connectMqtt(true)
            }

            override fun onError(errMsg: String) {
                onCancleLoading()
            }

        }, this)
    }

    private fun connectMqtt(isInit: Boolean) {
        if (TextUtils.isEmpty(mqttAccount) || TextUtils.isEmpty(mqttPsw)) {
            if (!isInit) {
                ToastUtils.showShortToast(this, "暂无设备信息，请通过网络配置获取设备信息")
            }
            return
        }
        if (MqttManager.getInstance().isConnect) {
            MqttManager.getInstance().disconnect()
        }
        mHandler.postDelayed({
//            showWaitDialog(R.string.waiting);
            onShowLoading()
            MqttManager.getInstance().setMqttMsg(mqttAccount, mqttPsw)
            MqttManager.getInstance().connect()
            mHandler.postDelayed({
                //Mqtt连接超时
                onCancleLoading()
                ToastUtils.showShortToast(this, "Mqtt连接超时")
                MqttManager.getInstance().disconnect()
            }, (10 * 1000).toLong())
        }, 500)
    }

//    private inner class MyHandler constructor(mHomeActivity7808: Home7808Activity7808) : Handler() {
//        var mHomeActivity7506WeakReference: WeakReference<Home7808Activity7808>
//        override fun handleMessage(msg: Message) {
//            val mHomeActivity7808 = mHomeActivity7506WeakReference.get()
//            if (mHomeActivity7808 != null) {
//                when (msg.what) {
//                    1 -> {
//                        val `object` = msg.obj as SocketModel
//                        if (`object`.key != null && `object`.value != null) {
//                            if (`object`.key == CommmandNum.mStatusTIME) {
////                                mTime = object.getValue();
//                            }
//                            Log.e("getSocket", `object`.name + "===" + `object`.key + "====" + `object`.value)
//                            DataManager.getInst().putKeyValue(`object`.key, `object`.value)
//                            SocketDataObserver.getInst().noticeSocket(`object`)
//                        }
//                    }
//                }
//            }
//        }
//        init {
//            mHomeActivity7506WeakReference = WeakReference(mHomeActivity7808)
//        }
//    }

    private fun chekcUpData() {
        Handler().post {
            //如果进入应用时没检查 则再检查一次更新
//            if (null == DataManager.getInst().getmUpdataBean()) {
                //检查网络更新
//                CommondManager.getInst().getUpdata(this@Home7808Activity7808, object : GetUpdataCallback {
//                    override fun onGetOnlineSuccess(program: BaseResponse<BeanUpdata>) {
//                        Log.e("checkUpdata", "checkUpdata_succeed")
//                        DataManager.getInst().isHasCheckUpdataOk = true
//                        val bean = program.data
//                        if (bean.isupgrade == 1) {
//                            if (bean.isforce == 1) {
//                                mSp!!.setStringValueAndCommit(Constants.SAVE_VERSION, bean.appversion)
//                                mSp!!.setIntValueAndCommit(Constants.SAVE_COUNT, 0)
//                                doUpdata(bean)
//                            } else {
//                                if (mSaveVersion != bean.appversion) {
//                                    mSp!!.setStringValueAndCommit(Constants.SAVE_VERSION, bean.appversion)
//                                    mSp!!.setIntValueAndCommit(Constants.SAVE_COUNT, 1)
//                                    doUpdata(bean)
//                                } else if (mSaveCount <= 3) {
//                                    mSp!!.setIntValueAndCommit(Constants.SAVE_COUNT, mSaveCount + 1)
//                                    doUpdata(bean)
//                                }
//                            }
//                        }
//                    }
//
//                    override fun onGetOnlineFailure() {
//                        DataManager.getInst().isHasCheckUpdataOk = false
//                        Log.e("checkUpdata", "checkUpdata_onGetOnlineFailure")
//                    }
//                })
//            }
        }
    }

    internal inner class NetworkChangeReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (CommonUtil.isFastClick()) {
                return
            }
            Log.e("TopActivity", CommonUtil.ActivityTop(this@Home7808Activity7808) + "")
            if (!CommonUtil.isActivityTop(SoftApNewActivity::class.java, this@Home7808Activity7808)
                    && !CommonUtil.isActivityTop(SoftApOldActivity::class.java, this@Home7808Activity7808)
                    && !CommonUtil.ActivityTop(this@Home7808Activity7808).contains("WifiSettingsActivity")) {
                val connectivityManager = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
                val networkInfo = connectivityManager.activeNetworkInfo
                if (networkInfo != null && networkInfo.isAvailable) {
                    Log.e("NetWork", "当前网络可用")
                    DataManager.inst.isNetCanUse = true
                    chekcUpData()
                    mTvNoNet!!.visibility = View.GONE
                    if (isFirst) {
                        isFirst = false
                        return
                    }
                    if (!hasFristConnect) {
                    }
                } else {
                    Log.e("NetWork", "当前网络不可用")
                    mRlRunning!!.visibility = View.GONE
                    mTvNoNet!!.visibility = View.VISIBLE
                    if (isFirst) {
                        isFirst = false
                        return
                    }
                }
            }
        }
    }
}